package com.security.admin.web;

import com.security.admin.model.Credentials;
import com.security.admin.model.TokenInfo;
import com.security.admin.util.RestUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author yanggld
 * @Date 2020/3/11-18:19
 */
@Slf4j
@Controller
public class DefaultController {

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/")
    public String root() {
        return "redirect:/index";
    }

    @GetMapping("/index")
    public String index() {
        return "index";
    }

    @GetMapping("/home")
    public String home() {


        return "home";
    }

    @GetMapping("/login")
    public String login() {
        return "login";
    }

    @GetMapping("/login-code")
    public String loginCode() {
        return "login-code";
    }

    @GetMapping("/login-error")
    public String loginError(Model model) {
        model.addAttribute("loginError", true);
        return login();
    }

    @GetMapping("/oauth/callback")
    public String callback(@RequestParam String code, @RequestParam String state, HttpServletResponse response,
        HttpServletRequest request) {
        log.info("*****oauth callback,code = {}", code);
        log.info("*****oauth callback,state = {}", state);
        String oauthUrl = "http://localhost:6100/auth/oauth/token";
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        httpHeaders.setBasicAuth("admin", "123456");
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("code", code);
        params.add("grant_type", "authorization_code");
        params.add("redirect_uri", "http://localhost:6090/oauth/callback");
        HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(params, httpHeaders);
        try {
            ResponseEntity<TokenInfo> responseEntity =
                restTemplate.exchange(oauthUrl, HttpMethod.POST, httpEntity, TokenInfo.class);
            log.info("登录获取token:{}", responseEntity.getBody().toString());
            TokenInfo tokenInfo = responseEntity.getBody();
            Cookie cookie = new Cookie("access_token", tokenInfo.getAccess_token());
            cookie.setMaxAge(tokenInfo.getExpires_in().intValue() - 3);
            cookie.setPath("/");
            response.addCookie(cookie);

            Cookie refreshTokenCookie = new Cookie("refresh_token",tokenInfo.getRefresh_token());
            refreshTokenCookie.setMaxAge(2592000);
            refreshTokenCookie.setPath("/");
            response.addCookie(refreshTokenCookie);

            request.getSession().setAttribute("token",tokenInfo);
        } catch (Exception e) {
            log.error(e.getMessage());
            String result = RestUtil.getCause(restTemplate);
            throw new RuntimeException(result);
        }
        return "login-code";
    }


}